package fr.insee.solr.service.impl;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

import fr.insee.solr.model.annotation.CachAnnotation;
import fr.insee.solr.model.annotation.SolrField;
import fr.insee.solr.model.annotation.SolrFields;
import fr.insee.solr.service.SolrReadService;
import fr.insee.solr.service.state.StateFactory;

public class SolrBeanRequest<U> implements SolrReadService<U>{
	

	@Override
	public List<U> makeBeans(List<Map<String, Object>> docFields, Class<U> clazz) throws SolrInseeException {
		Field[] simplefield = CachAnnotation.getSolrfield(clazz);
		Field[] arrayfield = CachAnnotation.getSolrfields(clazz);		
		
		List<U> beans = new ArrayList<U>();	
		
		for(Map<String,Object> doc : docFields){
			try {
				U bean = clazz.newInstance();
				this.fillSolrfield(bean, simplefield,doc);
				this.fillSolrfields(bean, arrayfield,doc);
				
				beans.add(bean);
			} catch (InstantiationException | IllegalAccessException e) {
				throw new SolrInseeException("Impossible d'instancier le type du bean : "+clazz.toString(),e);
			}
		}
		
		return beans;
	}
	
	private void fillSolrfields(U bean,Field[] fields,Map<String,Object> solrValues) throws SolrInseeException{
		for(Field f : fields){
			SolrFields sf = f.getAnnotation(SolrFields.class);
			for(SolrField a : sf.fields()){
				if(solrValues.containsKey(a.fieldName()) && a.read()){
					this.fillSingle(bean, f, a, solrValues.get(a.fieldName()));
				}
			}
		}
	}
	
	private void fillSolrfield(U bean,Field[] fields,Map<String,Object> solrValues) throws SolrInseeException{
		for(Field f : fields){
			SolrField a = f.getAnnotation(SolrField.class);
			if(solrValues.containsKey(a.fieldName()) && a.read()){
				this.fillSingle(bean, f, a, solrValues.get(a.fieldName()));
			}
		}
	}

	private void fillSingle(U bean,Field f,SolrField a,Object solrValue) throws SolrInseeException{
		StateFactory.getState(a).fillValue(bean,f,a,solrValue);
	}

}
